﻿using Aribaccio.Core;
using Aribaccio.Logger;
using BDPAutodetect.Mgrcore;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace BDPAutodetect.Client
{
    /// <summary>
    /// 菜单窗体视图模型
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public partial class MenuViewModel<T> : BaseViewModel<T> where T : class
    {
        /// <summary>
        /// 用户管理实例
        /// </summary>
        public UserManager UserMgr { get; protected set; }
        /// <summary>
        /// 角色权限管理实例
        /// </summary>
        public RolePowerManager RolePowerMgr { get; protected set; }
        /// <summary>
        /// 页面绑定内容
        /// </summary>
        [ObservableProperty]
        protected FrameworkElement? mainContent;
        /// <summary>
        /// 权限菜单集合
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MPowerMenu> powerMenus;
        /// <summary>
        /// 权限菜单连接字典【key:MPowerMenu, value:View】
        /// </summary>
        protected ConcurrentDictionary<MPowerMenu, ITransferView<UserControl>> PowerMenuPairs { get; set; }

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public MenuViewModel(UserManager argUserManager, RolePowerManager argRolePowerManager)
            : base()
        {
            this.UserMgr = argUserManager;
            this.RolePowerMgr = argRolePowerManager;
            this.PowerMenus = new ObservableCollection<MPowerMenu>();
            this.PowerMenuPairs = new ConcurrentDictionary<MPowerMenu, ITransferView<UserControl>>();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        [RelayCommand]
        public virtual async Task ExecuteLoaded()
        {
            if (this.IsLoaded) return;
            int nRoleID = this.UserMgr.LoginUser?.Role?.ID ?? 0;
            int nPowerID = this.PowerPermission?.Power.ID ?? 0;
            var resultMenus = this.RolePowerMgr.GetPowerMenus(nRoleID, nPowerID);
            if (resultMenus == null || resultMenus.Count <= 0) return;
            //循环添加权限菜单
            foreach (var pMenu in resultMenus)
            {
                this.PowerMenus.Add(pMenu);
            }
            //初始化菜单栏控件
            var resultTaskView = this.AddPowerMenuContentView();
            await resultTaskView.ConfigureAwait(false);
            //初始化加载主页
            var resultTaskNav = this.ExecuteMenuChanged(this.PowerMenus.First());
            await resultTaskNav.ConfigureAwait(false);
            this.IsLoaded = true;
        }

        /// <summary>
        /// 导航切换操作事件
        /// </summary>
        [RelayCommand]
        public virtual async Task ExecuteMenuChanged(MPowerMenu argPowerMenu)
        {
            if (!this.IsExecutedIdle) return;
            this.IsExecutedIdle = false;
            var resultTaskTransfer = this.GetMenuMainContent(argPowerMenu);
            await resultTaskTransfer.ConfigureAwait(false);
            this.IsExecutedIdle = true;
        }

        /// <summary>
        /// 初始化菜单栏控件
        /// </summary>
        protected virtual async Task AddPowerMenuContentView()
        {
            if (this.PowerMenus == null || this.PowerMenus.Count <= 0) return;
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    //获取跳转页面
                    ITransferView<UserControl>? resultTransferView = null;
                    foreach (var item in this.PowerMenus)
                    {
                        if (item == null) continue;
                        switch (item.Url)
                        {
                            //主窗体一级菜单
                            case "MainPage":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<MainPageView>();
                                break;
                            case "Parameter":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<ParameterView>();
                                break;
                            case "DetectTarget":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<DetectTargetView>();
                                break;
                            case "DetectRecord":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<DetectRecordView>();
                                break;                           
                            case "Setting":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<SettingView>();
                                break;
                            //设置界面二级树形菜单
                            case "SettingSystem":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<SettingSystemView>();
                                break;
                            case "SettingStation":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<SettingStationView>();
                                break;
                            case "SettingTarget":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<SettingTargetView>();
                                break;
                            case "SettingDeviceSlave":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<SettingDeviceSlaveView>();
                                break;
                            case "SettingDeviceChannel":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<SettingDeviceChannelView>();
                                break;
                            case "SettingUserRole":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<SettingUserRoleView>();
                                break;
                            case "SettingRolePower":
                                resultTransferView = ContainerManager.Instance.GetContainerServiceRequired<SettingRolePowerView>();
                                break;
                      
                        }
                        if (resultTransferView == null) continue;

                        resultTransferView.TransferPowerPermission(item.PowerPermission);
                        this.PowerMenuPairs.TryAdd(item, resultTransferView);
                    }
                }
                catch (Exception ep)
                {
                    LoggerMgrcore.Instance.WriteError("MainWindowModel InitPowerMenuContentView Exception", ep);
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }

        /// <summary>
        /// 获取菜单栏控件
        /// </summary>
        /// <param name="argPowerMenu">菜单栏参数</param>
        /// <returns></returns>
        protected virtual async Task<ITransferView<UserControl>?> GetMenuMainContent(MPowerMenu? argPowerMenu)
        {
            return await Task.Factory.StartNew(() =>
            {
                if (argPowerMenu == null || !this.PowerMenuPairs.ContainsKey(argPowerMenu)) return null;
                try
                {
                    //设置页面切换选中属性
                    foreach (var item in this.PowerMenus)
                    {
                        item.IsSelected = item.Equals(argPowerMenu);
                    }
                    //获取跳转页面
                    ITransferView<UserControl> resultTransferView = this.PowerMenuPairs[argPowerMenu];
                    //页面绑定到主窗体显示
                    this.MainContent = (UserControl)resultTransferView;
                    return resultTransferView;
                }
                catch (Exception ep)
                {
                    LoggerMgrcore.Instance.WriteError("MainWindowModel GetMenuMainContent Exception", ep);
                    return null;
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }
    }
}
